//树节点信息
var opernode = null;
var treeObj = null;

var menuCurLocation = null;//当前菜单显示位置信息
var menuCurTitle = null;//当前菜单显示标题
var menuCurDescription = null;//当前菜单显示描述

//菜单目录树形结构配置
var treeSetting = {
		view: {
			selectedMulti: false,
			dblClickExpand: false
		},
		check: {
			enable: false
		},
		edit: {
			enable: false,
			showRemoveBtn: false,
			showRenameBtn: false
		},
		data: {
			keep: {
				parent:false,
				leaf:false
			},
			 key:  {
		           name: "MENU_NAME",
			       title: "MENU_NAME"
			},
		     simpleData: {
				  enable: true,
				  idKey: "MENU_ID",
				  pIdKey: "PARENT_ID",
				  rootPId: ""
		    }
		},
		callback: {		
			onClick: TreeOnClick,
			onRightClick: OnRightClick
		}
	};

/*
 * {文档加载完成执行}
 */
$(document).ready(function(){
	initMenu();  
	initMenuInfoTree();
	bindEvent();	
	hideAllForm();
});

function initMenu(){
	//初始化页面左侧树右键菜单
	using('menu', function(){
		$('#rMenu').menu({
			onClick:function(item){
				switch (item.id) {
					case "addMenu":
						preAddMenu(item);
						break;
					case "deleteMenu":
						deleteMenu();
						break;				
					/*case "upShiftMenu":
						upShiftMenu();
						break;
					case "downShiftMenu":
						downShiftMenu();
						break;*/
					default:
						break;
				}
		 	}
		});
	});
}

function OnRightClick(event, treeId, treeNode) {
	opernode = treeNode;
	treeObj.selectNode(treeNode);
	hideAllForm();
	//设置树的节点的level大于等2时不能新建子菜单
  	if (opernode.level >= 2 ){
  		$("#rMenu").menu("disableItem",$("#addMenu"));
  	}else{
		$("#rMenu").menu("enableItem",$("#addMenu"));
  	}
  	//end modified
	$("#rMenu").menu("enableItem",$("#deleteMenu"));
	/*$("#rMenu").menu("enableItem",$("#upShiftMenu"));
	$("#rMenu").menu("enableItem",$("#downShiftMenu"));*/
	$('#rMenu').menu('show', {
		left: event.clientX,
		top: event.clientY
	});
}

/**
 * 事件绑定
 */
function bindEvent(){
    $("#save").bind("click",addOrEditMenu);
    $("#refresh").bind("click",refresh); 
    $("#reset").bind("click",resetForm);
    $("#createCustomMenu").bind("click",createCustomMenu);
    
} 

/**
 * 初始化左侧树控件
 */
function initMenuInfoTree(){
	$.ajax({
	   type: "POST",
	   async: false,//同步发送请求数据
	   url: appPath+"/menu?method=getTreeData",
	   data : {},
	   beforeSend : function(){
//		   $.showProgress();
	   },
	   complete : function(){
//		   $.hideProgress();
	   },
	   timeout:120*1000,
	   dataType:"json",
       success: function(data){
    	   if(data){
    		   var queryTreeNodeData = data;
	   		   if(queryTreeNodeData.length==0){
	   			   $.messageBox.alert({title : '错误',content : '查不到数据!'});
	   		   }
	   		   if(queryTreeNodeData.length>0){//初始化左边树控件
	   		       $.fn.zTree.init($("#menuTree"), treeSetting,queryTreeNodeData); 
	   		       treeObj = $.fn.zTree.getZTreeObj("menuTree");	//参数为树id
	   		   }   
    	   }else{
    		   $.messageBox.alert({title : '异常',content : '获取菜单信息异常!'}); 
    	   }
	   },
	   error:function(xhr,textStatus,errorThrown){
		   $.hideprogress();
	       $.messageBox.alert({title : '错误',content : textStatus});
	   }
	});
    
}


function createCustomMenu(){
	$.ajax({
		   type: "POST",
		   async: false,//同步发送请求数据
		   url: appPath+"/menu?method=createCustomMenu",
		   beforeSend : function(){
//			   $.showProgress();
		   },
		   complete : function(){
//			   $.hideProgress();
		   },
		   timeout:120*1000,
		   dataType:"json",
	       success: function(data){
	    	   if(data){
	    		   $("#alert").html(data.detail);
	    	   }
		   },
		   error:function(xhr,textStatus,errorThrown){
		   }
		});
}

/**
 * 重置
 */
function resetForm(){
	var MENU_ID = $('#MENU_ID').val();
	if(!($.isEmpty(MENU_ID))){
		$('#TITLE').val(menuCurTitle);
		$('#LOCATION').val(menuCurLocation);
		$('#DESCRIPTION').val(menuCurDescription);
	}
}

/**
 * 刷新
 */
function refresh(){
	hideAllForm();
	initMenuInfoTree();
}

function hideAllForm(){
//	$("#menuInfo").hide();
	$("#MenuInfoForm").hide();
}

function preAddMenu(menuItem){
	hideAllForm();	 
//	$("#menuInfo").show();
	$("#MenuInfoForm").show();
	$("#alert").html('<strong>注意!</strong> 请完善菜单信息。');
	//清空表单
	$(':input')   
	 .not(':button, :submit, :reset,:radio')   
	 .val('')   
	 .removeAttr('checked')   
	 .removeAttr('selected');  
	var data = opernode;
	if ( data.MENU_NUM != undefined ){
		if ( data.MENU_TYPE == "1" ){
			$('#custom_menu').attr("checked","checked");
		} else if ( data.MENU_TYPE == "0" ){
			$('#normal_menu').attr("checked","checked");
		}
	}
    $('#PARENT_ID').val(data.MENU_ID);
    var id = data.children == undefined ? 1 : data.children.length+1;
    var menu_num = data.MENU_NUM == undefined ? id : data.MENU_NUM +''+id;
    $('#MENU_NUM').val(menu_num);
    
 }
 
function addOrEditMenu(){
	//表单校验
	/*$("#MenuInfoForm").validate({
		rules:{
			TITLE:{
				required:true
			}
		}
	});
	if($("#MenuInfoForm").valid() == false){
		return;
	}*/
	var MENU_NAME = $('#MENU_NAME').val();
	var MENU_ID = $('#MENU_ID').val();
	var menuData = getFormData('MenuInfoForm');
	
	var isEdit = false;
	if($.isEmpty(MENU_ID)){//新增节点
		//判断同一目录下有没有相同相同名称节点
		var childnodes = opernode.children;
		var childnodesLen = null;
	    if (childnodes != null){
	    	childnodesLen = childnodes.length;
		    for(var i=0;i<childnodesLen;i++){
		    	if(childnodes[i].MENU_NAME == MENU_NAME){
//		    		$.messageBox.alert({title : '错误',content : '同一目录下，该菜单项题目已经存在'});
		    		return;
		    	}
		    }
	    }else{
	    	childnodesLen = 0;
	    }
	    isEdit = false;
	    menuData.ORDER_SORT = childnodesLen+1;
	}else{//编辑节点
		//判断同一目录下有没有相同相同名称节点
		var nodeName = opernode.MENU_NAME;//节点名称
		if(nodeName != MENU_NAME){
			var nodes = treeObj.getNodesByParam("MENU_NAME",MENU_NAME);
			if(nodes.length>0){
				$.messageBox.alert({title : '错误',content : '同一目录下，该菜单项题目已经存在'});
	    		return;
			}
		}
		isEdit = true;
	}	
	$.ajax({
		   type: "POST",
		   async: false,//同步发送请求数据
		   url : appPath+'/menu?method=addOrEditMenu',		 
		   data : {
			   'data' : $.toJSONString(menuData)
		   },
		   beforeSend : function(){
			   $('#save').button('loading');
		   },
		   complete : function(){
			   $('#save').button('reset');
		   },
		   timeout:120*1000,
		   dataType:"json",
		   success: function(res){
			   if(res){
				    var status = res.status;
		    		var detail = res.detail;
		    		if(status=='-1'){//异常
//		    			$.messageBox.alert({title : '异常',content : detail});
//						 initMenuInfoTree();
		    		}else{//正常
//			    		 $.messageBox.alert({title : '成功',content : detail});
		    			$("#alert").html(detail);
		    			 if(isEdit){
		    				 opernode.TITLE = res.TITLE;
		    				 opernode.LOCATION = res.LOCATION;				      
		    				 opernode.DESCRIPTION = res.DESCRIPTION;
		    				 treeObj.updateNode(opernode);
		    				 treeObj.selectNode(opernode);
		    			 }else{
		    				 try{
		    		 			 var nodes = treeObj.addNodes(opernode, res);//在父节点下面加入新建节点到尾部
		    	             	 if(nodes && nodes.length>0){
		    		             	var node = nodes[0]; //选中唯一一个匹配的节点
		    		             	treeObj.selectNode(node);
		    		             	opernode = node;
		    		                TreeOnClick(null, null, node);
		    	             	  }
		    	 			 }catch(e){
		    	 				 initMenuInfoTree();
		    	 			 } 
		    			}
				   }
			   }else{
//				   $.messageBox.alert({title : '异常',content : '操作出现异常'});
				   $("#alert").html('操作出现异常');
			   }
		   },
		   error:function(xhr,textStatus,errorThrown){
			   $('#save').button('reset');
//			   $.messageBox.alert({title : '异常',content : '操作出现异常'});
			   $("#alert").html('操作出现异常');
		   }
		});
}
/*
 * 处理左键单击节点事件
 */
function TreeOnClick(event, treeId, treeNode) {
	opernode = treeNode;
    var nodeData = treeNode;//单击的节点
	var form = null; 
    if(nodeData.MENU_ID != '0'){//处理中间节点和叶子节点  
	    $('#MenuInfoForm').show();
	    //清空表单
	    $(':input')   
		 .not(':button, :submit, :reset, :radio')   
		 .val('')   
		 .removeAttr('checked')   
		 .removeAttr('selected');

	    $('#MENU_ID').val(nodeData.MENU_ID);	
		$('#MENU_NUM').val(nodeData.MENU_NUM);
		$('#MENU_NAME').val(nodeData.MENU_NAME);
		$('#MENU_LOCATION').val(nodeData.MENU_LOCATION);
		$('#MENU_DESC').val(nodeData.MENU_DESC);

		if ( nodeData.MENU_TYPE == "1" ){
			$('#custom_menu').attr("checked","checked");
		} else if ( nodeData.MENU_TYPE == "0" ){
			$('#normal_menu').attr("checked","checked");
		}
//		$('#MENU_TYPE').val(nodeData.MENU_TYPE); 
	    menuCurLocation = nodeData.LOCATION;
	    menuCurTitle = nodeData.TITLE;
	    menuCurDescription = nodeData.DESCRIPTION;
  	}
}
 
/**
 * 删除节点
 * @returns {Boolean}
 */
function deleteMenu(){
	var curNode = opernode;
    var selectedNode = treeObj.getSelectedNodes()[0];
	if(selectedNode.children!=null && selectedNode.children.length>0){
		$("#alert").html('存在子节点，不能删除！');
		return false;
	}
	$.ajax({
	   type: "POST",
	   async: false,//同步发送请求数据
	   url : appPath+'/menu?method=deleteMenu',
	   data : {
		   'data' : $.toJSONString(selectedNode)
	   },
	   error : function(xhr,status,errorThrown){
		   $.messageBox.alert({title : '异常',content : '操作出现异常'});
		   initMenuInfoTree();
	   },
	   beforeSend : function(){
//				   $.showProgress();
	   },
	   complete : function(){
//				   $.hideProgress();
	   },
	   timeout:120*1000,
	   dataType:"json",
	   success: function(res){
		   if(res){
			   var status = res.status;
			   var detail = res.detail;
			   if(status=='-1'){
				   $.messageBox.alert({title : '异常',content : detail});
			   }else{
				   $.messageBox.alert({title : '提示信息',content : detail});
				   var parentNode = selectedNode.getParentNode();
				   //修改被选中节点后面所有的兄弟节点,让他们的ORDER_SORT属性值减1
				   if(parentNode.childs!=null && parentNode.childs.length>0){
					   var len = parentNode.childs.length;
					   for(var j=0;j<len;j++){
						   if(parentNode.childs[j].ORDER_SORT > selectedNode.ORDER_SORT){
							   parentNode.childs[j].ORDER_SORT = parentNode.childs[j].ORDER_SORT-1;
						   } 
					   }
					}
					//删除被选中的节点
					treeObj.removeNode(selectedNode);
					treeObj.selectNode(parentNode,false);
					TreeOnClick(null, null, parentNode);
			   }	 
		   }else{
			   $.messageBox.alert({title : '异常',content : '操作出现异常'});
		   }
	  }
	});
}

